package com.globaldom.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.CivResource;
import com.globaldom.model.Person;
import com.globaldom.model.Research;
import com.globaldom.model.Science;
import com.globaldom.utils.Constants;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/research")
public class ResearchController {
	public ResearchController() {
	}
	// private static final Logger log =
	// Logger.getLogger(ResearchController.class.getName());

	/*
	 */
	@RequestMapping(value = "/do", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> addCivilian(@RequestParam Long researchID, HttpSession session, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		String personID = SessionManager.getID(request, session);
		if (null == personID) {
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "401");
			return map;
		}

		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			Science s = pm.getObjectById(Science.class, researchID);
			if (null == s)
				throw new RuntimeException("wot?");
			int dollars = s.getResearchAmount();
			Person p = pm.getObjectById(Person.class, personID);
			if (p.getLevel() < s.getMinLevel())
				throw new RuntimeException("Invalid level!");
			// Check if the research has already been done!
			Query query = pm.newQuery(Research.class, "scienceID==signsid && personID==pid");
			query.declareParameters("long signsid,String pid");
			if (((List<Research>) query.execute(researchID, personID)).size() > 0) {
				throw new RuntimeException("Already Researched!");
			}
			int resStatus = 1;
			query = pm.newQuery(Research.class, "researchComplete==1 && personID==pid");
			query.declareParameters("String pid");

			if (((List<Research>) query.execute()).size() > 0)
				resStatus = 2;
			Research r = new Research();
			r.setPersonID(personID);
			r.setScienceID(researchID);
			r.setResearchType(s.getResearchType());
			r.setResearchComplete(resStatus);
			pm.makePersistent(r);

			PersistenceManager pmciv = PMF.get().getPersistenceManager();
			// query = pmciv.newQuery(CivResource.class,
			// "person==pid && ResType==restype");
			// query.declareParameters("String pid,int restype");
			// // query.declareParameters("");
			// CivResource cvdollar = (CivResource) query.execute(personID,
			// CivResource.DOLLAR);

			CivResource cvdollar = pmciv.getObjectById(CivResource.class, personID + "/" + CivResource.DOLLAR);

			long newval = cvdollar.getResAvailable() - dollars;
			if (newval < 0) {
				throw new RuntimeException("Insufficient Money!");
			}
			cvdollar.setResAvailable(newval);

			pmciv.close();

			map.put(Constants.STATUS, "+OK");
			// MemCacheManager.addResearch(personID, r);
		} catch (RuntimeException rte) {
			map.put(Constants.STATUS, "+-ER");
			map.put(Constants.CODE, rte.getMessage());
			// MemCacheManager.removeResearch(personID);
		} catch (Exception ex) {
			// log.severe("Error during transaction" + ex);
			map.put(Constants.STATUS, "+-ER");
			map.put(Constants.CODE, ex.getLocalizedMessage());

		} finally {

			pm.close();

		}

		return map;
	}
}
